package com.jtpay.payresulthelper.http.dataStructure;

import android.annotation.SuppressLint;
import com.google.gson.Gson;
import com.jtpay.payresulthelper.util.LogUtil;
import com.jtpay.payresulthelper.util.PayDESUtil;
import com.jtpay.payresulthelper.util.PayMD5Util;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by Administrator on 2018/1/25.
 * JSON的装换类与RequestBody的包装类
 */

public class JsonParams extends HashMap<String, Object> {
    public RequestBody buildJsonRequestBody() {
        LogUtil.log("buildJsonRequestBody  " + toString());
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(this));
    }

    public RequestBody buildRequestBody() {
        LogUtil.log("buildRequestBody  " + toString());
        FormBody.Builder builder = new FormBody.Builder();
        for (Entry<String, Object> entry : entrySet()) {
            builder.add(entry.getKey(), entry.getValue().toString());
        }
        return builder.build();
    }

    public RequestBody getDesRequestBody() {
        @SuppressLint("SimpleDateFormat")
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String nonce = PayMD5Util.getMD5(dateFormat.format(new Date()));
        String str = getJsonObject();
        String replace = str.replace("\\/", "/");
        LogUtil.log("mObject.toString() = " + replace);

        String encodeMsg = PayDESUtil.encodeVerifyDef(nonce, replace);
        LogUtil.log("PayDESUtil.nonce = " + nonce);
        LogUtil.log("PayDESUtil.encode = " + encodeMsg);
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("nonce", nonce);
        builder.add("msg", encodeMsg);
        return builder.build();
    }

    public String getJsonObject() {
        return new Gson().toJson(this);
    }

    @Override
    public String toString() {
        return "JsonParams: " + getJsonObject();
    }

    /**
     * @return des EncodeObject
     */
    public String getEncodeObject() {
        LogUtil.log(toString());
        return PayDESUtil.encodeDef(getJsonObject()).replace("\"", "");
    }

}
